<?php

class LanguageProductAPIService extends FServiceBase
{
    /**
     * Get a LanguageProduct model given its ID
     *
     * @param int id LanguageProduct ID
     * @return FServiceModel
     */
    public function get($params)
    {
        $model = LanguageProduct::model()->findByPk($this->getParam($params, 'id', 0));
        if (!$model)
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('Product.LanguageProduct', 'Invalid ID.'));
        $this->result->processed('model', $model);
        return $this->result;
    }

    public function save($params)
    {
        $model = $this->getModel($params['LanguageProduct'], 'LanguageProduct');
        $this->result->processed('model', $model);

        if (!$model->validate()) {
            $this->result->fail(ERROR_INVALID_DATA, Yii::t('Product.LanguageProduct', 'Submitted data is missing or invalid.'));
            Yii::trace($model->getErrors());
        } elseif ($this->getParam($params, 'validateOnly', 0) == TRUE) {
            return $this->result;
        } elseif (!$model->save(false)) {
            // we can save without validation as the model has been validated
            $this->result->fail(ERROR_HANDLING_DB, Yii::t('Product.LanguageProduct', 'Error while saving submitted data into database.'));
        }
        return $this->result;
    }


    public function delete($params)
    {
        $ids = $this->getParam($params, 'ids', array());
        if ($ids == 0) {
            return $this->result->fail(ERROR_INVALID_DATA, Yii::t('Product.LanguageProduct', 'Invalid ID.'));
        }

        if (!is_array($ids)) $ids = array($ids);
        foreach ($ids as $id) {
            $model = LanguageProduct::model()->findByPk($id);
            /**
             * TODO: Check related data if this LanguageProduct is deletable
             * This can be done in onBeforeDelete or here or in extensions
             *
            if (Related::model()->count("LanguageProductId = {$id}") > 0)
            $this->result->fail(ERROR_VIOLATING_BUSINESS_RULES, Yii::t('Product.LanguageProduct',"Cannot delete LanguageProduct ID={$id} as it has related class data."));
            else
             */
            try {
                $model->delete();
            } catch (CDbException $ex) {
                $this->result->fail(ERROR_HANDLING_DB, $ex->getMessage());
            }
        }
        return $this->result;
    }
}